package ru.kreda.webapp.client.ui;

import com.extjs.gxt.ui.client.core.El;
import com.extjs.gxt.ui.client.util.Size;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Container;
import com.extjs.gxt.ui.client.widget.Layout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;

/**
 * {@link FitLayout}, с возможностью установить минимальные размеры панели,
 * после которых можгут появиться скроллеры.
 */
public class ScrollableFitLayout extends Layout {
	private final int minWidth;
	private final int minHeight;

	public ScrollableFitLayout(int minWidth, int minHeight) {
		monitorResize = true;
		this.minWidth = minWidth;
		this.minHeight = minHeight;
	}

	public ScrollableFitLayout() {
		this(-1, -1);
	}

	@Override
	protected void onLayout(Container<?> container, El target) {
		if (container.getItemCount() == 0) {
			return;
		}
		activeItem = activeItem != null ? activeItem : container.getItem(0);
		super.onLayout(container, target);

		setItemSize(activeItem, target.getStyleSize());
	}

	private void setItemSize(Component item, Size size) {
		if (minWidth != -1 && size.width < minWidth) {
			size.width = minWidth;
		}
		if (minHeight != -1 && size.height < minHeight) {
			size.height = minHeight;
		}
		if (item != null && item.isRendered()) {
			size.width -= getSideMargins(item);
			size.height -= item.el().getMargins("tb");
			setSize(item, size.width, size.height);
		}
	}

}
